 package com.ebo.learn_demo

import java.lang.reflect.Method
import java.lang.reflect.Proxy

 /**
 * @author zmp
 * @date : 2021/12/10 17:09
 * des:TODO
 */
object MathEngine {

    inline fun <reified T> createMath(): T {
        return Proxy.newProxyInstance(
            javaClass.classLoader, arrayOf(T::class.java)
        ) { _, p1: Method, p2 ->
            val annotation = p1.getAnnotation(IMethod::class.java)
            val mReturnType = p1.returnType
            println("p2 ---  ${p2.size}")
            println("annotation:$annotation Method $p1")
            var result = 0.toDouble()
            when (annotation.values) {
                IMethodType.METHOD_ADD -> {
                    for (element in p2[0] as Array<*>) {
                        println("element $element")
                        result += if (element is Number) {
                            element.toDouble()
                        } else {
                            (element.toString()).toDouble()
                        }
                    }
                }
                IMethodType.METHOD_MINUS -> {
                    for (element in p2) {

                        result -= (element as Number).toDouble()
                    }
                }
                IMethodType.METHOD_MULTIPLY -> {
                    for (element in p2) {
                        result *= (element as Number).toDouble()
                    }
                }
                IMethodType.METHOD_DIVIDE -> {
                    for (element in p2) {
                        result /= (element as Number).toDouble()
                    }
                }
            }
            when (mReturnType) {
                Int::class.java -> {
                    result.toInt()
                }
                Float::class.java -> {
                    result.toFloat()
                }
                else -> {
                    result
                }
            }

        } as T
    }
}